package com.gitee.exercisedemo.retry;

import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SpringRetryDemo {
    private static final int MAX_ATTEMPTS = 3;
    private static final long DELAY_TIME = 1000 * 60 * 2L;
    private static final int MULTIPLIER = 2;

    /**
     * backoff：重试的时候等待 5S, 后面时间依次变为原来的 2 倍数
     */
    @Retryable(value = Exception.class, maxAttempts = MAX_ATTEMPTS, backoff = @Backoff(delay = DELAY_TIME, multiplier = MULTIPLIER))
    public void call(RetryableObj obj) throws Exception {
        if (!obj.isSuccess()) {
            obj.setRetriedCount(obj.getRetriedCount() + 1);
            log.info("重试:{}次,最大重试次数:{}", obj.getRetriedCount(), MAX_ATTEMPTS);
            throw new Exception("模拟异常");
        }
        obj.setSuccess(true);
    }


    @Recover
    private void recover(Exception exception) {
        log.error("超出重试次数");
        log.error("异常信息：", exception);
    }
}
